package gw.com.android.ui.home;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import gw.com.android.presenter.http.HomeGainListRequest;
import gw.com.android.presenter.http.HomePlatformOperationDataRequest;
import gw.com.android.utils.FontUtils;
import gw.com.android.utils.PackStatis;

/**
 * 首页，盈利榜单
 * <p>
 * 看来这里是给他构建数据的
 */
public class HomeGainListView extends LinearLayout {

    private LinearLayout ll_gain_list, ll_single_gain_list, ll_no_data;//这里有两个表格
    private TextView tv_workTime, tv_tradesCount, tv_registersCount, tv_current_day, tv_unit_3, tv_unit_2, tv_unit_1;

    private Context mContext;

    public HomeGainListView(Context context) {
        this(context, null);
    }

    public HomeGainListView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HomeGainListView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }


    class GainData {
        int sort;
        String account;
        String gain;
        String gainRate;
        String winRate;
    }

    class SingleGainData {
        int sort;
        String product;
        String gain;
        String openDate;
        String closeDate;
    }

    List<GainData> gainListDataList = new ArrayList<>();//盈利榜数据
    List<SingleGainData> singleGainDataList = new ArrayList<>();//单日盈利榜


    @Override
    protected void onFinishInflate() {//  这个构造方法···？
        super.onFinishInflate();
        initTab();
        initPlatformDataView();
    }

    Typeface font;

    private void initPlatformDataView() {
        font = FontUtils.getDIN_MediumFont(getContext());
        tv_workTime = (TextView) findViewById(R.id.tv_workTime);
        tv_workTime.setTypeface(font);
        tv_tradesCount = (TextView) findViewById(R.id.tv_tradesCount);
        tv_tradesCount.setTypeface(font);
        tv_registersCount = (TextView) findViewById(R.id.tv_registersCount);
        tv_registersCount.setTypeface(font);

        tv_unit_1 = findViewById(R.id.tv_unit_1);
        tv_unit_2 = findViewById(R.id.tv_unit_2);
        tv_unit_3 = findViewById(R.id.tv_unit_3);
    }

    private void initGridView() {
        tv_current_day.setText(updateTime);

        //清除全部子之后，添加上表头
        ll_gain_list.removeAllViews();
        LayoutInflater.from(mContext).inflate(R.layout.layout_grid_header, ll_gain_list, true);

        for (int i = 0; i < gainListDataList.size(); i++) {
            View dataRoot = LayoutInflater.from(mContext).inflate(R.layout.layout_grid_data, ll_gain_list, false);
            TextView tv_sort = (TextView) dataRoot.findViewById(R.id.tv_sort);
            ImageView iv_front_3 = (ImageView) dataRoot.findViewById(R.id.iv_front_3);
            dealSort(gainListDataList.get(i).sort, tv_sort, iv_front_3);

            TextView tv_account = (TextView) dataRoot.findViewById(R.id.tv_account);
            tv_account.setText(gainListDataList.get(i).account);

            TextView tv_gain = (TextView) dataRoot.findViewById(R.id.tv_gain);
            tv_gain.setText(gainListDataList.get(i).gain);
            tv_gain.setTypeface(font);

            TextView tv_gain_rate = (TextView) dataRoot.findViewById(R.id.tv_gain_rate);
            tv_gain_rate.setText(gainListDataList.get(i).gainRate);

            TextView tv_win_rate = (TextView) dataRoot.findViewById(R.id.tv_win_rate);
            tv_win_rate.setText(gainListDataList.get(i).winRate);

            ll_gain_list.addView(dataRoot);
        }


        ll_single_gain_list.removeAllViews();
        LayoutInflater.from(mContext).inflate(R.layout.layout_grid_header_s, ll_single_gain_list, true);
        for (int i = 0; i < singleGainDataList.size(); i++) {
            View dataRoot = LayoutInflater.from(mContext).inflate(R.layout.layout_grid_data_s, ll_single_gain_list, false);
            TextView tv_sort = (TextView) dataRoot.findViewById(R.id.tv_sort);
            ImageView iv_front_3 = (ImageView) dataRoot.findViewById(R.id.iv_front_3);
            dealSort(singleGainDataList.get(i).sort, tv_sort, iv_front_3);

            TextView tv_product = (TextView) dataRoot.findViewById(R.id.tv_product);
            tv_product.setText(singleGainDataList.get(i).product);

            TextView tv_gain = (TextView) dataRoot.findViewById(R.id.tv_gain);
            tv_gain.setText(singleGainDataList.get(i).gain);
            tv_gain.setTypeface(font);

            TextView tv_open_date = (TextView) dataRoot.findViewById(R.id.tv_open_date);
            tv_open_date.setText(singleGainDataList.get(i).openDate);

            TextView tv_close_date = (TextView) dataRoot.findViewById(R.id.tv_close_date);
            tv_close_date.setText(singleGainDataList.get(i).closeDate);

            ll_single_gain_list.addView(dataRoot);
        }
    }

    /**
     * 处理前三名，用图片表示排名; 其他的显示成数字
     *
     * @param i
     * @param tv_sort
     * @param iv
     */
    private void dealSort(int i, TextView tv_sort, ImageView iv) {
        if (i <= 3) {
            tv_sort.setVisibility(View.GONE);
            iv.setVisibility(View.VISIBLE);
            if (i == 1) {
                iv.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.a_first));
            } else if (i == 2) {
                iv.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.a_second));
            } else if (i == 3) {
                iv.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.a_third));
            }
        } else {
            tv_sort.setVisibility(View.VISIBLE);
            iv.setVisibility(View.GONE);
            tv_sort.setText(String.valueOf(i));
            tv_sort.setTypeface(font);
        }
    }

    // tab 切换逻辑
    private LinearLayout ll_tab1, ll_tab2;
    private TextView tv_tab1, tv_tab2;
    private View iv_tab1, iv_tab2;

    private void initTab() {
        ll_tab1 = (LinearLayout) findViewById(R.id.ll_tab1);
        ll_tab2 = (LinearLayout) findViewById(R.id.ll_tab2);
        tv_tab1 = (TextView) findViewById(R.id.tv_tab1);
        tv_tab2 = (TextView) findViewById(R.id.tv_tab2);
        iv_tab1 = findViewById(R.id.iv_tab1);
        iv_tab2 = findViewById(R.id.iv_tab2);
        tv_tab1.getPaint().setFakeBoldText(true);//设置为粗体字
        tv_tab1.postInvalidate();

        ll_tab1.setOnClickListener(tabClickLis);
        ll_tab2.setOnClickListener(tabClickLis);

        ll_gain_list = (LinearLayout) findViewById(R.id.ll_gain_list);
        ll_single_gain_list = (LinearLayout) findViewById(R.id.ll_single_gain_list);
        ll_no_data = (LinearLayout) findViewById(R.id.ll_no_data);
        tv_current_day = (TextView) findViewById(R.id.tv_current_day);
    }

    private static final int COLOR_NOT_CHECK = 0XFF666666;
    private static final int COLOR_CHECKED = 0xFF333333;

    private int currentTab = 0;
    private OnClickListener tabClickLis = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (ll_gain_list == null) return;
            if (ifAnimating)
                valueAnimator.cancel();
            if (v.getId() == ll_tab1.getId()) {
                if (currentTab == 0)
                    return;
                Log.d("PackStatisTag", "盈利榜");
                PackStatis.getToService(PackStatis.EventAction.CLICKPROFITLIST1.getValue(), PackStatis.EventCategory.HOME.getValue(), null, null);
                currentTab = 0;
                switchViews(iv_tab1, iv_tab2, tv_tab1, tv_tab2);//tab上的文字图片发生变化
                initTabChangeAnimator(0, 1);//显示第一个表格，隐藏第二个表格
            } else if (v.getId() == ll_tab2.getId()) {
                if (currentTab == 1)
                    return;
                Log.d("PackStatisTag", "单笔最高盈利");
                PackStatis.getToService(PackStatis.EventAction.CLICKPROFITLIST2.getValue(), PackStatis.EventCategory.HOME.getValue(), null, null);
                currentTab = 1;
                switchViews(iv_tab2, iv_tab1, tv_tab2, tv_tab1);
                initTabChangeAnimator(1, 0);//显示第二个表格，隐藏第一个表格
            } else {
            }
        }
    };

    private void switchViews(View ivToShow, View ivToHide, TextView tvToBold, TextView tvToNotBold) {
        tvToBold.getPaint().setFakeBoldText(true);//设置为粗体字
        tvToBold.postInvalidate();
        tvToNotBold.getPaint().setFakeBoldText(false);
        tvToNotBold.postInvalidate();

        tvToBold.setTextColor(COLOR_CHECKED);
        tvToNotBold.setTextColor(COLOR_NOT_CHECK);

        ivToShow.setVisibility(View.VISIBLE);
        ivToHide.setVisibility(View.GONE);
    }

    private boolean ifAnimating = false;// 是否正在执行动画
    private ValueAnimator valueAnimator;

    //做一个透明度变化的过度效果，突然这么切过来很僵硬
    private void initTabChangeAnimator(int start, int end) {
        valueAnimator = ValueAnimator.ofFloat(start, end);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ifAnimating = true;
                float f = (float) animation.getAnimatedValue();
                ll_gain_list.setAlpha(f);
                ll_single_gain_list.setAlpha(1 - f);
                iv_tab1.setAlpha(f);
                iv_tab2.setAlpha(1 - f);
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ifAnimating = false;
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                ifAnimating = true;
            }
        });
        valueAnimator.setDuration(300);
        valueAnimator.start();
    }

    private void initDemoData() {
        //造点假数据
        gainListDataList = new ArrayList<>();
        GainData gainData;
        for (int i = 1; i <= 5; i++) {
            gainData = new GainData();
            gainData.sort = i;
            gainData.account = "000" + i + " ****";
            gainData.gain = (5 - i) + "00";
            gainData.winRate = (10 - i) + "0%";
            gainData.gainRate = (10 - i) + "0%";

            gainListDataList.add(gainData);
        }

        singleGainDataList = new ArrayList<>();
        SingleGainData singleGainData;
        for (int i = 1; i <= 5; i++) {
            singleGainData = new SingleGainData();

            singleGainData.sort = i;
            singleGainData.product = i < 3 ? "伦敦金" : "伦敦银";
            singleGainData.gain = (5 - i) + "00";
            singleGainData.openDate = "06-12";
            singleGainData.closeDate = "07-12";

            singleGainDataList.add(singleGainData);
        }
    }

    public void refresh(HomeGainListRequest.HomeGainListData homeGainListData) {
        if (homeGainListData == null) {
            ll_no_data.setVisibility(VISIBLE);

            tv_current_day.setVisibility(GONE);
            ll_gain_list.setVisibility(GONE);
            ll_single_gain_list.setVisibility(GONE);
            return;
        } else {
            ll_no_data.setVisibility(GONE);

            tv_current_day.setVisibility(VISIBLE);
            ll_gain_list.setVisibility(VISIBLE);
            ll_single_gain_list.setVisibility(VISIBLE);
        }

        // 解析数据，更新视图 tv_current_day
        List<HomeGainListRequest.GainList> gainListData = homeGainListData.gainListData;
        gainListDataList = new ArrayList<>();//本类中使用的数据结构
        GainData gainData;
        for (int i = 1; i <= gainListData.size(); i++) {
            gainData = new GainData();
            gainData.sort = i;
            gainData.account = gainListData.get(i - 1).login;
            gainData.gain = String.valueOf(Math.round(gainListData.get(i - 1).profit));
            gainData.winRate = dealStr(gainListData.get(i - 1).trade_winning);
            gainData.gainRate = dealStr(gainListData.get(i - 1).yield);
            updateTime = gainListData.get(i - 1).release_date;
            gainListDataList.add(gainData);
        }

        // 一个一个加载
        List<HomeGainListRequest.GainSingleList> gainSingleListData = homeGainListData.gainSingleListData;
        singleGainDataList = new ArrayList<>();
        SingleGainData singleGainData;
        for (int i = 1; i <= gainSingleListData.size(); i++) {
            singleGainData = new SingleGainData();

            singleGainData.sort = i;
            singleGainData.product = gainSingleListData.get(i - 1).symbol;
            singleGainData.gain = String.valueOf(Math.round(gainSingleListData.get(i - 1).highest_profit));
            singleGainData.openDate = splitDateStr(gainSingleListData.get(i - 1).open_date);
            singleGainData.closeDate = splitDateStr(gainSingleListData.get(i - 1).close_date);

            singleGainDataList.add(singleGainData);
        }
        initGridView();
    }

    private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd");

    private String splitDateStr(String dateStr) {
        String str = "";
        try {
            Date d = sdf1.parse(dateStr);
            str = sdf2.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return str;
    }

    // 有可能接到 19.00%这样的字符串，现在要把小数点后面小数只保留一个小数位
    private String dealStr(String param) {
        //先把数字截取出来
        String temp = param.replace("%", "");//19.00 String
        Double d = Double.parseDouble(temp);//19.0 Double
        return String.format("%.1f", d) + "%";//19.0% String
    }

    public void refreshPlatformOperationData(HomePlatformOperationDataRequest.PlatformOperationData data) {
        if (data == null) {
            tv_workTime.setText(tempEmpty);
            tv_tradesCount.setText(tempEmpty);
            tv_registersCount.setText(tempEmpty);

            tv_unit_1.setVisibility(GONE);
            tv_unit_2.setVisibility(GONE);
            tv_unit_3.setVisibility(GONE);

        } else {
            tv_workTime.setText(dealWorkTime(data.workTime));
            tv_tradesCount.setText(dealNum(data.tradesCount));
            tv_registersCount.setText(dealNum(data.registersCount));

            tv_unit_1.setVisibility(VISIBLE);
            tv_unit_2.setVisibility(VISIBLE);
            tv_unit_3.setVisibility(VISIBLE);
        }
    }

    //现在，把这3个数据处理
    // 2955,15:14:32  我知道了，她的意思是，服务了这么多天，这么多个小时，分钟秒数
    // 只保留天数就好
    private String tempEmpty = "--";

    private String dealWorkTime(String str) {
        if (TextUtils.isEmpty(str))
            return tempEmpty;
        if (!str.contains(",")) {
            return tempEmpty;
        }
        return str.split(",")[0];
    }

    private String dealNum(String str) {
        int res = 0;
        try {
            int intValue = Integer.parseInt(str);//先转化成数字
            res = intValue / 10000; //转化成N万级别
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(res);
    }

    private String updateTime = "";

}
